package ruifeng.zcj.communcationring.base.base_web_activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;
import com.rey.material.widget.ProgressView;


import butterknife.Bind;
import ruifeng.zcj.communcationring.R;
import ruifeng.zcj.communcationring.base.App;
import ruifeng.zcj.communcationring.base.BaseActivity;
import ruifeng.zcj.communcationring.base.base_web_activity.other.JS;
import ruifeng.zcj.communcationring.groble.Whole;

/**
 * Created by Administrator on 2016/8/23 0023.
 */
public abstract class WebViewActivity extends BaseActivity implements
        SwipeRefreshLayout.OnRefreshListener, JS.JSListener {
    public static final String KEY_CLASS_NAME = "className";
    public static final String KEY_ARGS = "args";

    @Bind(R.id.layoutLoading)
    LinearLayout layoutLoading;
    @Bind(R.id.layoutContent)
    LinearLayout mLayoutContent;

    @Bind(R.id.layoutLoadFailed)
    LinearLayout layoutLoadFailed;
    @Bind(R.id.layoutEmpty)
    LinearLayout layoutEmpty;
    @Bind(R.id.progress)
    ProgressView mProgress;
    @Bind(R.id.webview)
    public WebView mWebview;
    @Bind(R.id.txtLoadFailed)
    TextView mTxtLoadFailed;
    @Bind(R.id.txtLoadEmpty)
    TextView mTxtLoadEmpty;
    @Bind(R.id.txtLayoutReload)
    TextView mTxtLayoutReload;

    @Bind(R.id.refreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;

    public WebSettings ws;
    public String MyURL;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    public interface TextViewChanger {
        void changeText(String arg);
    }

    private TextViewChanger mTextChanger = new TextViewChanger() {// 回调方法
        @Override
        public void changeText(final String arg) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pay(arg);
                }
            });
        }
    };

    // js代码调用java代码之后该做什么事情做什么事情
    public void pay(String arg) {

    }

    @Override
    public void initView() {
        showLoadingDialog("正在加载");

        ws = mWebview.getSettings();
        ws.setJavaScriptEnabled(true);
        if (isCacheMode()) {// 是否设置缓存
            //  ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //设置 缓存模式(true);
        }
        ws.setAppCacheEnabled(true);
        ws.setSupportZoom(false);
        ws.setUseWideViewPort(true);// 可任意比例缩放
        ws.setJavaScriptCanOpenWindowsAutomatically(true);// js支持
        ws.setDomStorageEnabled(true);

        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.equals(Whole.web_public2)) {

                    finishActivity();
                }
                return WebViewActivity.this.shouldOverrideUrlLoading(view, url);
            }

            /***
             * 判断有网络情况下，页面出错误了才会调用这个方法
             * */
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                dismissLoadingDialog();
                if (errorCode == -2) {
                    layoutLoadFailedVisibility(true);
                    Toast.makeText(App.getAppContext(), "网络连接失败 ,请连接网络。", Toast.LENGTH_SHORT).show();
                    view.setVisibility(View.INVISIBLE);
                } else {// 失败-10
                    layoutEmptyVisibility(true);
                    Toast.makeText(App.getAppContext(), "网速较慢 ,请刷新。", Toast.LENGTH_SHORT).show();
                }
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (mProgress != null) {
                    //  mProgress.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dismissLoadingDialog();
                if (mProgress != null) {
                    mProgress.setVisibility(View.GONE);
                }
                if (isRefreshing()) {
                    hideSwipeRefreshing();
                }
                layoutLoadingVisibility(false);
            }
        });
        mWebview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
              /*  if (newProgress < 100) {
                    if (mProgress != null) {
                        mProgress.setVisibility(View.VISIBLE);
                    }

                } else if (newProgress == 100) {
                    if (mProgress != null) {
                        mProgress.setVisibility(View.GONE);
                    }
                }
                if (mProgress != null) {
                    mProgress.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);*/
            }
        });

        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);


        if (isAddJavascriptInterface()) {
            AddJavascript();
        }
        mWebview.loadUrl(getURL());
    }

    public String getURL() {
        if (!TextUtils.isEmpty(MyURL)) {
            return MyURL;
        } else {
            layoutLoadFailedVisibility(false);
            layoutEmptyVisibility(true);
            layoutContentVisibility(false);
            layoutLoadingVisibility(false);
        }
        return null;
    }

    // 是否调用js代码默认是传递
    protected boolean isAddJavascriptInterface() {
        return false;
    }

    // 传递一个类给html
    public void AddJavascript() {
        JS js = newJsObj();
        js.setTextChanger(mTextChanger);// 把接口发送过去,之后会回调,js调java
        js.setShareListener(this);
        mWebview.addJavascriptInterface(js, HTMLkey());
        // JS js = TUtil.getT(this, 0);
        // js.setTextChanger(mTextChanger);// 把接口发送过去,之后会回调,js调java
//        mWebview.addJavascriptInterface(js,"webview");
    }

    // new一个子类
    public JS newJsObj() {// 传递一个子类给
        return null;
    }


    // 一个key
    public String HTMLkey() {// 获取他的key
        return "Android";
    }


    public abstract boolean shouldOverrideUrlLoading(WebView view, String url);


    public void layoutLoadingVisibility(boolean isVisible) {
        if (layoutLoading != null) {
            RxView.visibility(layoutLoading, View.GONE).call(isVisible);
        }
    }

    public void layoutContentVisibility(boolean isVisible) {
        if (mLayoutContent != null) {
            RxView.visibility(mLayoutContent, View.GONE).call(isVisible);
        }
    }

    public void layoutLoadFailedVisibility(boolean isVisible) {
        if (layoutLoadFailed != null) {
            RxView.visibility(layoutLoadFailed, View.GONE).call(isVisible);
        }
    }

    public void layoutEmptyVisibility(boolean isVisible) {
        if (layoutEmpty != null) {
            RxView.visibility(layoutEmpty, View.GONE).call(isVisible);
        }
    }

    public void showSwipeRefreshing() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(true);
        }
    }

    public void hideSwipeRefreshing() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    public boolean isRefreshing() {
        if (swipeRefreshLayout != null) {
            return swipeRefreshLayout.isRefreshing();
        }
        return false;
    }


    @Override
    public void onRefresh() {
        if (mWebview != null) {
            mWebview.reload();
            layoutLoadFailedVisibility(false);
            layoutEmptyVisibility(false);
            layoutContentVisibility(true);
//            layoutLoadingVisibility(true);
            mWebview.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 如果
            if (!TextUtils.isEmpty(MyURL) && !MyURL.equals(mWebview.getUrl())) {
                mWebview.goBack();
            } else if (MyURL.equals(mWebview.getUrl()) && !TextUtils.isEmpty(MyURL)) {
//                CircleAcvitity.this.finish();
                finishActivity();
            }
        }
        return false;
    }

    public void finishActivity() {
    }

    public boolean isCacheMode() {
        return true;
    }

    @Override
    public void uploadfileimg(String param) {

    }
}
